<template>
  <div class="">
    <el-form size="small" :inline="true" class="query-form" ref="searchForm" :model="searchForm"
             @keyup.enter.native="refreshList()" @submit.native.prevent>
      <!-- 搜索框-->
      <el-form-item prop="patientName">
        <el-input size="small" v-model="searchForm.patientName" placeholder="姓名" clearable></el-input>
      </el-form-item>
      <el-form-item prop="idCardNumber">
        <el-input size="small" v-model="searchForm.idCardNumber" placeholder="身份证号" clearable></el-input>
      </el-form-item>
      <el-form-item prop="patientPhone">
        <el-input size="small" v-model="searchForm.patientPhone" placeholder="手机号" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="refreshList()" size="small" icon="el-icon-search">查询</el-button>
        <el-button @click="resetSearch()" size="small" icon="el-icon-refresh-right">重置</el-button>
      </el-form-item>
    </el-form>

    <div style="background-color: #F2F6FC" class="top">
<!--      <vxe-toolbar :refresh="{query: refreshList}" import export print custom>
        <template #tools>
          <vxe-button
            type="default"
            title="下载导入模板"
            v-if="hasPermission('patient:patientInfo:import')"
            class="el-icon-document m-r-12"
            @click="downloadTpl()"
            circle
          >
          </vxe-button>
        </template>
      </vxe-toolbar>-->
      <div style="height: calc(100% - 80px);padding: 0 60px;">

        <div >
          <el-row :gutter="40">
            <el-col :span="6" v-for="(item,index) in dataList">
              <div style="margin-top: 20px;" @click="showDetail(item)">
                <el-card style="cursor: pointer;" >

                  <el-row :gutter="20" style="height: 220px;">
                    <el-col :span="12">
                      <img style="width: 100%" height="200px" class="hide-sm"
                           :src="item.photo === ''?'/static/img/avatar.png':item.photo">
                    </el-col>
                    <el-col :span="12">
                      <div style="font-size: 18px;font-weight: bold;">{{ item.patientName }}</div>
                      <div class="info-item">性别：<span>{{ $dictUtils.getDictLabel("sex", item.gender, '-') }}</span></div>
                      <div class="info-item">年龄：<span>{{ item.age }}</span></div>
                      <div class="info-item">身份证号：<span>{{ item.idCardNumber }} </span></div>
<!--                      <div class="info-item">电话：<span>{{ item.patientPhone }}</span></div>-->
<!--                      <div class="info-item">简介：<span>{{ item.doctorDesc }}</span></div>-->
                    </el-col>
                  </el-row>

                </el-card>
              </div>
            </el-col>
          </el-row>
        </div>

<!--        <vxe-table
          border="inner"
          auto-resize
          resizable
          height="auto"
          :loading="loading"
          size="small"
          ref="patientInfoTable"
          show-header-overflow
          show-overflow
          highlight-hover-row
          :menu-config="{}"
          :print-config="{}"
          :import-config="{
            importMethod: importMethod,
                types: ['csv', 'xls', 'xlsx'],
                remote: true,
            }"
          :export-config="{
                remote: true,
                filename: `病人信息数据${moment(new Date()).format(
            		'YYYY-MM-DD'
                )}`,
                sheetName: '病人信息数据',
                exportMethod: exportMethod,
                types: ['xlsx'],
                modes: ['current', 'selected', 'all'],
            }"
          @sort-change="sortChangeHandle"
          :sort-config="{remote:true}"
          :data="dataList"
          :checkbox-config="{}">
          <vxe-column type="checkbox" width="40px"></vxe-column>
          <vxe-column
            field="patientName"
            sortable
            title="姓名">
            <template slot-scope="scope">
              <el-link type="primary" :underline="false" v-if="hasPermission('patient:patientInfo:edit')"
                       @click="edit(scope.row.id)">{{scope.row.patientName}}
              </el-link>
              <el-link type="primary" :underline="false" v-else-if="hasPermission('patient:patientInfo:view')"
                       @click="view(scope.row.id)">{{scope.row.patientName}}
              </el-link>
              <span v-else>{{scope.row.patientName}}</span>
            </template>
          </vxe-column>
          <vxe-column
            field="idCardNumber"
            width="180"
            title="身份证号">
          </vxe-column>
          <vxe-column
            field="gender"
            title="性别">
            <template slot-scope="scope">
              {{ $dictUtils.getDictLabel("sex", scope.row.gender, '-') }}
            </template>
          </vxe-column>
          <vxe-column
            field="age"
            title="年龄">
          </vxe-column>
          <vxe-column
            field="patientPhone"
            width="120"
            title="手机号">
          </vxe-column>
          <vxe-column
            field="birthDate"
            width="180"
            title="出生日期">
          </vxe-column>
          <vxe-column
            field="address"
            title="住址">
          </vxe-column>
          <vxe-column
            field="createDate"
            width="180"
            title="创建时间">
          </vxe-column>
          <vxe-column
            fixed="right"
            align="center"
            width="240"
            title="操作">
            <template slot-scope="scope">
              <el-button v-if="hasPermission('patient:patientInfo:follow')" type="text" size="small"
                         @click="huiFang(scope.row.id)">回访记录
              </el-button>
              <el-button v-if="hasPermission('patient:patientInfo:visit')" type="text" size="small"
                         @click="jiuZhen(scope.row.id)">就诊记录
              </el-button>

              <el-button v-if="hasPermission('patient:patientInfo:visit')" type="text" size="small"
                         @click="jiuZhenTimeLine(scope.row.id)">就诊跟踪
              </el-button>

              <el-divider direction="vertical"></el-divider>
              <el-dropdown size="small" @command="handleCommand">
                    <span class="el-dropdown-link">
                      更多<i class="el-icon-arrow-down el-icon&#45;&#45;right"></i>
                    </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-if="hasPermission('patient:patientInfo:view')"
                                    :command="{method:'view', id:scope.row.id}">
                    查看
                  </el-dropdown-item>
                  <el-dropdown-item v-if="hasPermission('patient:patientInfo:edit')"
                                    :command="{method:'edit', id:scope.row.id}">
                    修改
                  </el-dropdown-item>
                  <el-dropdown-item v-if="hasPermission('patient:patientInfo:del')"
                                    :command="{method:'del', id:scope.row.id}">
                    删除
                  </el-dropdown-item>
                  <el-dropdown-item v-if="hasPermission('patient:patientInfo:bill')"
                                    :command="{method:'bill', row:scope.row}">
                    费用清单
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </vxe-column>
        </vxe-table>-->
        <vxe-pager
          background
          size="small"
          :current-page="tablePage.currentPage"
          :page-size="tablePage.pageSize"
          :total="tablePage.total"
          :page-sizes="[10, 20, 100, 1000, {label: '全量数据', value: 1000000}]"
          :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
          @page-change="currentChangeHandle">
        </vxe-pager>
      </div>
    </div>
    <!-- 弹窗, 新增 / 修改 -->
    <PatientInfoForm ref="patientInfoForm" @refreshDataList="refreshList"></PatientInfoForm>
    <!--回访记录-->
    <el-dialog
      title="回访记录"
      :visible.sync="followDialogVisible"
      width="80%">
      <div>
        <vxe-table
          border="inner"
          auto-resize
          resizable
          :loading="loading"
          size="small"
          ref="followUpInfoTable"
          show-header-overflow
          show-overflow
          highlight-hover-row
          :menu-config="{}"
          :print-config="{}"
          @sort-change="sortChangeHandle"
          :sort-config="{remote:true}"
          :data="followDataList"
        >
          <vxe-column type="checkbox" width="40px"></vxe-column>
          <vxe-column
            field="followName"
            title="回访名称">
            <template slot-scope="scope">
              <el-link type="primary" :underline="false" v-if="hasPermission('follow:followUpInfo:edit')"
                       @click="edit(scope.row.id)">{{scope.row.followName}}
              </el-link>
              <el-link type="primary" :underline="false" v-else-if="hasPermission('follow:followUpInfo:view')"
                       @click="view(scope.row.id)">{{scope.row.followName}}
              </el-link>
              <span v-else>{{scope.row.followName}}</span>
            </template>
          </vxe-column>
          <vxe-column
            field=""

            title="病人姓名">
            <template slot-scope="scope">
              {{scope.row.patientInfo.patientName}}
            </template>
          </vxe-column>
          <vxe-column
            field=""
            sortable
            title="医生姓名">
            <template slot-scope="scope">
              {{scope.row.doctorInfo.doctorName}}
            </template>
          </vxe-column>
          <vxe-column
            field="healthStatus"
            title="健康状态">
          </vxe-column>
          <vxe-column
            field="followUpDate"
            sortable
            title="回访时间">
          </vxe-column>
        </vxe-table>
        <vxe-pager
          background
          size="small"
          :current-page="followTablePage.currentPage"
          :page-size="followTablePage.pageSize"
          :total="followTablePage.total"
          :page-sizes="[10, 20, 100, 1000, {label: '全量数据', value: 1000000}]"
          :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
          @page-change="currentChangeHandle">
        </vxe-pager>
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button @click="followDialogVisible = false">关 闭</el-button>
  </span>
    </el-dialog>

    <!--就诊记录-->
    <el-dialog
      title="就诊记录"
      :visible.sync="visitDialogVisible"
      width="80%">
      <div style="height: calc(100% - 80px);">
        <vxe-table
          border="inner"
          auto-resize
          resizable
          :loading="loading"
          size="small"
          ref="visitInfoTable"
          show-header-overflow
          show-overflow
          highlight-hover-row
          :menu-config="{}"
          :print-config="{}"
          @sort-change="sortChangeHandle"
          :sort-config="{remote:true}"
          :data="visitDataList"
          :checkbox-config="{}">
          <vxe-column type="checkbox" width="40px"></vxe-column>
          <vxe-column
            field="visitDataList"
            title="就诊记录">
            <template slot-scope="scope">
              <el-link type="primary" :underline="false" v-if="hasPermission('visit:visitInfo:edit')"
                       @click="edit(scope.row.id)">{{scope.row.visitRecord}}
              </el-link>
              <el-link type="primary" :underline="false" v-else-if="hasPermission('visit:visitInfo:view')"
                       @click="view(scope.row.id)">{{scope.row.visitRecord}}
              </el-link>
              <span v-else>{{scope.row.visitRecord}}</span>
            </template>
          </vxe-column>
          <vxe-column
            field=""
            sortable
            title="患者姓名">
            <template slot-scope="scope">
              {{scope.row.patientInfo.patientName}}
            </template>
          </vxe-column>
          <vxe-column
            field=""
            title="主治医生">
            <template slot-scope="scope">
              {{scope.row.doctorInfo.doctorName}}
            </template>
          </vxe-column>
          <vxe-column
            field="departmentId"
            title="就诊科室">
            <template slot-scope="scope">
              {{$officeUtils.getOfficeName(scope.row.departmentId,'--')}}
            </template>
          </vxe-column>
          <vxe-column
            field="visitTime"
            sortable
            title="就诊时间">
          </vxe-column>
          <vxe-column
            field="diagnosis"
            title="诊断结果">
          </vxe-column>
          <!-- <vxe-column
             field="prescription"
             title="处方">
           </vxe-column>-->

          <vxe-column
            field="updateDate"
            sortable
            title="更新时间">
          </vxe-column>
        </vxe-table>
        <vxe-pager
          background
          size="small"
          :current-page="visitTablePage.currentPage"
          :page-size="visitTablePage.pageSize"
          :total="visitTablePage.total"
          :page-sizes="[10, 20, 100, 1000, {label: '全量数据', value: 1000000}]"
          :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
          @page-change="currentChangeHandle">
        </vxe-pager>
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button @click="visitDialogVisible = false">关 闭</el-button>
  </span>
    </el-dialog>

    <!--费用清单-->
    <el-dialog
      title="费用清单"
      :visible.sync="billDialogVisible"
      width="80%">
      <div>
        <vxe-table
          border="inner"
          auto-resize
          resizable
          :loading="loading"
          size="small"
          ref="billingInfoTable"
          show-header-overflow
          show-overflow
          highlight-hover-row
          :menu-config="{}"
          :print-config="{}"
          @sort-change="sortChangeHandle"
          :sort-config="{remote:true}"
          :data="billDataList"
          :checkbox-config="{}">
          <vxe-column type="checkbox" width="40px"></vxe-column>
          <vxe-column
            field="patientId"
            title="患者姓名">
            <template slot-scope="scope">
              <el-link type="primary" :underline="false" v-if="hasPermission('billing:billingInfo:edit')"
                       @click="edit(scope.row.id)">{{scope.row.patientInfo.patientName}}
              </el-link>
              <el-link type="primary" :underline="false" v-else-if="hasPermission('billing:billingInfo:view')"
                       @click="view(scope.row.id)">{{scope.row.patientInfo.patientName}}
              </el-link>
              <span v-else>{{scope.row.patientInfo.patientName}}</span>
            </template>
          </vxe-column>
          <vxe-column
            field="visitId"
            title="就诊记录">
            <template slot-scope="scope">
              {{ scope.row.visitInfo.visitRecord}}
            </template>
          </vxe-column>
          <vxe-column
            field="consumptionItem"
            title="消费项">
            <template slot-scope="scope">
              {{scope.row.drugInfo.drugName }}
            </template>
          </vxe-column>
          <vxe-column
            field="unitPrice"
            title="单价">
          </vxe-column>
          <vxe-column
            field="amount"
            title="数量">
          </vxe-column>
          <vxe-column
            field="cost"
            title="费用金额">
          </vxe-column>
          <vxe-column
            field="paymentMethod"
            title="支付方式">
            <template slot-scope="scope">
              {{ $dictUtils.getDictLabel("payment_method", scope.row.paymentMethod, '-') }}
            </template>
          </vxe-column>
          <vxe-column
            field="paymentStatus"
            title="支付状态">
            <template slot-scope="scope">
              {{ $dictUtils.getDictLabel("application_state", scope.row.paymentStatus, '-') }}
            </template>
          </vxe-column>
        </vxe-table>
        <vxe-pager
          background
          size="small"
          :current-page="billTablePage.currentPage"
          :page-size="billTablePage.pageSize"
          :total="billTablePage.total"
          :page-sizes="[12, 24, 100, 1000, {label: '全量数据', value: 1000000}]"
          :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
          @page-change="currentChangeHandle">
        </vxe-pager>
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button @click="billDialogVisible = false">关 闭</el-button>
  </span>
    </el-dialog>

    <Report ref="report"></Report>

  </div>
</template>

<script>
  import PatientInfoForm from './PatientInfoForm'
  import patientInfoService from '@/api/patient/patientInfoService'
  import followUpInfoService from '@/api/follow/followUpInfoService'
  import visitInfoService from '@/api/visit/visitInfoService'
  import billingInfoService from '@/api/billing/billingInfoService'
  import userService from '@/api/sys/userService'
  import Report from '@/views/modules/patient/report.vue'

export default {
    data () {
      return {
        searchForm: {
          patientName: '',
          idCardNumber: '',
          patientPhone: ''
        },
        dataList: [],
        tablePage: {
          total: 0,
          currentPage: 1,
          pageSize: 10,
          orders: [{column: 'create_date', asc: false}]
        },
        loading: false,
        followDialogVisible: false,
        followDataList: [],
        followTablePage: {
          total: 0,
          currentPage: 1,
          pageSize: 10,
          orders: [{column: 'a.create_date', asc: false}]
        },
        followSearchForm: {
          patientId: '',
          doctorId: ''
        },
        visitDialogVisible: false,
        timeLineDialogVisible: false,
        visitSearchForm: {
          patientId: '',
          doctorId: ''
        },
        visitDataList: [],
        visitTablePage: {
          total: 0,
          currentPage: 1,
          pageSize: 10,
          orders: [{column: 'a.create_date', asc: false}]
        },
        billSearchForm: {
          patientId: '',
          visitId: ''
        },
        billDataList: [],
        billTablePage: {
          total: 0,
          currentPage: 1,
          pageSize: 10,
          orders: [{column: 'a.create_date', asc: false}]
        },
        billDialogVisible: false
      }
    },
    components: {
      PatientInfoForm,
      Report
    },
    activated () {
      this.refreshList()
    },
    methods: {

      showDetail (item) {
        this.$refs.report.init(item)
      },

      bill (id) {
        this.billDialogVisible = true
        this.billSearchForm.patientId = id
        this.$nextTick(() => (
          this.billList()
        ))
      },
      // 获取数据列表
      billList () {
        this.loading = true
        billingInfoService.list({
          'current': this.billTablePage.currentPage,
          'size': this.billTablePage.pageSize,
          'orders': this.billTablePage.orders,
          ...this.billSearchForm
        }).then(({data}) => {
          this.billDataList = data.records
          this.billTablePage.total = data.total
          this.loading = false
        })
      },
      jiuZhen (id) {
        this.visitDialogVisible = true
        this.visitSearchForm.patientId = id
        this.$nextTick(() => (
          this.visitList()
        ))
      },

      jiuZhenTimeLine (id) {
        this.$refs.timeLine.init(id)
      },

      // 获取数据列表
      visitList () {
        this.loading = true
        visitInfoService.list({
          'current': this.visitTablePage.currentPage,
          'size': this.visitTablePage.pageSize,
          'orders': this.visitTablePage.orders,
          ...this.visitSearchForm
        }).then(({data}) => {
          this.visitDataList = data.records
          this.visitTablePage.total = data.total
          this.loading = false
        })
      },
      huiFang (id) {
        this.followDialogVisible = true
        this.followSearchForm.patientId = id
        this.$nextTick(() => (
          this.followList()
        ))
      },
      followList () {
        this.loading = true
        followUpInfoService.list({
          'current': this.followTablePage.currentPage,
          'size': this.followTablePage.pageSize,
          'orders': this.followTablePage.orders,
          ...this.followSearchForm
        }).then(({data}) => {
          this.followDataList = data.records
          this.followTablePage.total = data.total
          this.loading = false
        })
      },
      // 获取数据列表
      refreshList () {
        this.loading = true
        patientInfoService.list({
          'current': this.tablePage.currentPage,
          'size': this.tablePage.pageSize,
          'orders': this.tablePage.orders,
          ...this.searchForm
        }).then(({data}) => {
          let dataList = data.records
          this.tablePage.total = data.total
          console.log(this.dataList)
          let i = 0
          dataList.forEach(item => {
            userService.getPhotoById(item.id).then(res => {
              console.log(res)
              i++
              item.photo = res.data
              if (i === dataList.length) {
                this.dataList = dataList
                this.loading = false
              }
            })
          })
        })
      },
      // 当前页
      currentChangeHandle ({currentPage, pageSize}) {
        this.tablePage.currentPage = currentPage
        this.tablePage.pageSize = pageSize
        this.refreshList()
      },
      // 排序
      sortChangeHandle (obj) {
        this.tablePage.orders = []
        if (obj.order != null) {
          this.tablePage.orders = [{
            column: obj.column.sortBy || this.$utils.toLine(obj.property),
            asc: obj.order === 'asc'
          }]
        } else {
          this.tablePage.orders = [{column: 'create_date', asc: false}]
        }
        this.refreshList()
      },
      // 新增
      add () {
        this.$refs.patientInfoForm.init('add', '')
      },
      // 修改
      edit (id) {
        id = id || this.$refs.patientInfoTable.getCheckboxRecords().map(item => {
          return item.id
        })[0]
        this.$refs.patientInfoForm.init('edit', id)
      },
      // 查看
      view (id) {
        this.$refs.patientInfoForm.init('view', id)
      },
      // 删除
      del (id) {
        let ids = id || this.$refs.patientInfoTable.getCheckboxRecords().map(item => {
          return item.id
        }).join(',')
        this.$confirm(`确定删除所选项吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          patientInfoService.delete(ids).then(({data}) => {
            this.$message.success(data)
            this.refreshList()
            this.loading = false
          })
        })
      },
      // 下载模板
      downloadTpl () {
        this.loading = true
        patientInfoService.exportTemplate().then(({data}) => {
          // 将二进制流文件写入excel表，以下为重要步骤
          this.$utils.downloadExcel(data, '请假表单导入模板')
          this.loading = false
        }).catch(function (err) {
          this.loading = false
          if (err.response) {
            console.log(err.response)
          }
        })
      },
      // 自定义服务端导入
      importMethod ({file}) {
        // 处理表单
        const formBody = new FormData()
        formBody.append('file', file)
        this.loading = true
        patientInfoService.importExcel(formBody).then(({data}) => {
          this.$message.success({
            dangerouslyUseHTMLString: true,
            message: data
          })
          this.refreshList()
        })
      },
      // 自定义服务端导出
      exportMethod ({options}) {
        // 传给服务端的参数
        const params = {
          current: this.tablePage.currentPage,
          size: this.tablePage.pageSize,
          orders: this.tablePage.orders,
          ...this.searchForm,
          filename: options.filename,
          sheetName: options.sheetName,
          isHeader: options.isHeader,
          original: options.original,
          mode: options.mode,
          selectIds: options.mode === 'selected' ? options.data.map((item) => item.id) : [],
          exportFields: options.columns.map((column) => column.property && column.property.split('.')[0])
        }
        this.loading = true
        return patientInfoService.exportExcel(params).then(({data}) => {
          // 将二进制流文件写入excel表，以下为重要步骤
          this.$utils.downloadExcel(data, options.filename)
          this.loading = false
        }).catch(function (err) {
          if (err.response) {
            console.log(err.response)
          }
        })
      },
      resetSearch () {
        this.$refs.searchForm.resetFields()
        this.refreshList()
      },
      handleCommand (command) {
        if (command.method === 'view') {
          this.view(command.id)
        } else if (command.method === 'edit') {
          this.edit(command.id)
        } else if (command.method === 'del') {
          this.del(command.id)
        } else if (command.method === 'addChild') {
          this.addChild(command.row)
        } else if (command.method === 'bill') {
          this.bill(command.id)
        }
      },
      handleClose (done) {
        this.$confirm('确认关闭？').then(_ => {
          done()
        }).catch(_ => {
        })
      }
    }
  }
</script>

<style scoped lang="scss">
  .info-item {
    margin-top: 10px;
    font-size: 16px;
    color: #606266;
  }
</style>

